package top.lingchen.blogapi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.lingchen.blogapi.bean.Article;
import top.lingchen.blogapi.bean.ArticleBody;
import top.lingchen.blogapi.bean.ArticleTag;
import top.lingchen.blogapi.bean.SysUser;
import top.lingchen.blogapi.mapper.ArticleBodyMapper;
import top.lingchen.blogapi.mapper.ArticleMapper;
import top.lingchen.blogapi.mapper.ArticleTagMapper;
import top.lingchen.blogapi.service.*;
import top.lingchen.blogapi.utils.UserThreadLocal;
import top.lingchen.blogapi.vo.*;
import top.lingchen.blogapi.vo.params.ArticleParam;
import top.lingchen.blogapi.vo.params.PageParams;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author 凌宸
 * @create 2021-12-15 下午 9:19
 * @Description
 * @Version 1.0
 */
@Slf4j
@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private TagService tagService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private ThreadService threadService;

    @Override
    public Result listArticle(PageParams params){
        Page<Article> page = new Page<>(params.getPage(), params.getPageSize());

        IPage<Article> articleIPage = articleMapper.listArticle(page, params.getCategoryId(),
                params.getTagId(), params.getYear(), params.getMonth());
        List<Article> records = articleIPage.getRecords();
        return Result.success(copyList(records, true, true));
    }

//    @Override
//    public Result listArticle(PageParams params) {
////        log.info("ArticleServiceImpl");
//        /**
//         * 分页查询 article 数据库表
//         */
//        Page<Article> page = new Page<>(params.getPage(), params.getPageSize());
//        LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<>();
//        // 是否指定排序
//        // 按照创建时间倒序排列
//        if(params.getCategoryId() != null){
//            // 加入类别查询信息
//            wrapper.eq(Article::getCategoryId, params.getCategoryId());
//        }
//        List<Long> articleIdList = new ArrayList<>();
//        if(params.getTagId() != null){
//            LambdaQueryWrapper<ArticleTag> articleTagWrapper = new LambdaQueryWrapper<>();
//            articleTagWrapper.eq(ArticleTag::getTagId, params.getTagId());
//            List<ArticleTag> articleTags = articleTagMapper.selectList(articleTagWrapper);
//            for (ArticleTag articleTag : articleTags) {
//                articleIdList.add(articleTag.getArticleId());
//            }
//            if(articleIdList.size() > 0){
//                wrapper.in(Article::getId, articleIdList);
//            }
//        }
//        wrapper.orderByDesc(Article::getWeight, Article::getCreateDate);
//        Page<Article> articlePage = articleMapper.selectPage(page, wrapper);
//        List<Article> records = articlePage.getRecords();
//        List<ArticleVo> articleVoList = copyList(records, true, true);
////        log.info("articleVoList = {}" , articleVoList);
//        return Result.success(articleVoList);
//    }

    @Override
    public Result hotArticles(int limit) {
        LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(Article::getViewCounts);
        wrapper.select(Article::getId, Article::getTitle);
        wrapper.last("limit " + limit);
        // select id, title from article order by viewCounts desc limit 5
        List<Article> articles = articleMapper.selectList(wrapper);
        return Result.success(copyList(articles, false, false));
    }

    @Override
    public Result newArticles(int limit) {
        LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(Article::getCreateDate);
        wrapper.select(Article::getId, Article::getTitle);
        wrapper.last("limit " + limit);
        // select id, title from article order by viewCounts desc limit 5
        List<Article> articles = articleMapper.selectList(wrapper);
        return Result.success(copyList(articles, false, false));
    }

    @Override
    public Result listArchives() {
        List<Archives> archivesList = articleMapper.listArchives();
        return Result.success(archivesList);
    }

    private List<ArticleVo> copyList(List<Article> records, boolean isTag, boolean isAuthor) {
        List<ArticleVo> articleVoList = new ArrayList<>();
        for (Article article : records){
            articleVoList.add(copy(article, isTag, isAuthor, false, false));
        }
        return articleVoList;
    }

    private List<ArticleVo> copyList(List<Article> records, boolean isTag, boolean isAuthor, boolean isBody, boolean isCategory) {
        List<ArticleVo> articleVoList = new ArrayList<>();
        for (Article article : records){
            articleVoList.add(copy(article, isTag, isAuthor, isBody, isCategory));
        }
        return articleVoList;
    }


    @Override
    public Result findArticleById(Long articleId) {
        /**
         * 根据文章 id 查看文章信息
         * 根据 bodyId 和 categoryId 去做关联查询
         */
        Article article = articleMapper.selectById(articleId);
        log.info("article: {} ",article);
        ArticleVo articleVo = copy(article, true, true, true, true);
        // 查看完文章了，新增阅读数，
        // 查看完文章之后，本应该直接返回数据，这时候做了一个更新操作，更新时加写锁，阻塞其他的读操作，性能会比较低
        // 更新增加了此次接口的 耗时，如果一旦更新出问题，不能影响，查看文章的操作
        // 线程池 可以把更新操作扔到线程池中去执行，就与主线程无关了
        threadService.updateArctileViewCount(articleMapper, article);
        return Result.success(articleVo);
    }
    @Autowired
    private ArticleTagMapper articleTagMapper;

    @Override
    public Result publish(ArticleParam articleParam) {
        // 此接口的访问路径，需要加入到拦截器中
        SysUser sysUser = UserThreadLocal.get();
        /**
         * 发布文章 目的 构建 Article 对象
         * 作者 id 当前的登录用户
         * 标签，要将标签加入到 文章-标签 关联表中
         * body 内容存储，需要添加到 文章-内容 关联表中
         */
        Article article = new Article();
        article.setAuthorId(sysUser.getId());
        // 插入之后，拿到生成的 文章 id
        // 设置基本信息
        article.setWeight(Article.Article_Common);
        article.setViewCounts(0);
        article.setTitle(articleParam.getTitle());
        article.setSummary(articleParam.getSummary());
        article.setCommentCounts(0);
        article.setCreateDate(System.currentTimeMillis());
        article.setCategoryId(Long.parseLong(articleParam.getCategory().getId()));
        articleMapper.insert(article);
        // tag
        List<TagVo> tags = articleParam.getTags();
        Long articleId = article.getId();
        if(tags != null){
            for (TagVo tag : tags) {
                ArticleTag articleTag = new ArticleTag();
                articleTag.setTagId(Long.parseLong(tag.getId()));
                articleTag.setArticleId(articleId);
                articleTagMapper.insert(articleTag);
            }
        }
        // body
        ArticleBody articleBody = new ArticleBody();
        articleBody.setArticleId(articleId);
        articleBody.setContent(articleParam.getBody().getContent());
        articleBody.setContentHtml(articleParam.getBody().getContentHtml());
        articleBodyMapper.insert(articleBody);
        // 设置文章 body id
        article.setBodyId(articleBody.getId());
        articleMapper.updateById(article);
        Map<String, String> map = new HashMap<>();
        map.put("id", article.getId().toString());
        return Result.success(map);
    }

    @Autowired
    private CategoryService categoryService;


    private ArticleVo copy(Article article, boolean isTag, boolean isAuthor, boolean isBody, boolean isCategory){
        ArticleVo articleVo = new ArticleVo();
        BeanUtils.copyProperties(article, articleVo);
        articleVo.setId(String.valueOf(article.getId()));
        articleVo.setCreateDate(new DateTime(article.getCreateDate()).toString("yyyy-MM-dd HH:mm:ss"));
        // 并不是所有的接口，都需要标签和作者信息
        if(isTag){
            Long articleId = article.getId();
            articleVo.setTags(tagService.findTagsByArticleId(articleId));
        }
        if(isAuthor){
            Long authorId = article.getAuthorId();
            articleVo.setAuthor(sysUserService.findUserById(authorId).getNickname());
        }
        if(isBody){
            Long bodyId = article.getBodyId();
            articleVo.setBody(findArticleBodyById(bodyId));
        }
        if(isCategory){
            Long categoryId = article.getCategoryId();
            articleVo.setCategory(categoryService.findCategoryById(categoryId));
        }
        return articleVo;
    }

    @Autowired
    private ArticleBodyMapper articleBodyMapper;

    private ArticleBodyVo findArticleBodyById(Long bodyId) {
        ArticleBody articleBody = articleBodyMapper.selectById(bodyId);
        ArticleBodyVo articleBodyVo = new ArticleBodyVo();
        articleBodyVo.setContent(articleBody.getContent());
        return articleBodyVo;
    }

}
